from dotenv import load_dotenv,find_dotenv
from openai import OpenAI
import os
import json
import requests

amap_key = "6d672e6194caa3b639fccf2caf06c342"
"""
_= ... 这里使用下划线 _ 是一种惯例，通常表示我们不打算使用函数的返回值，
因为 load_dotenv() 返回的是加载的环境变量字典或者 None，我们不关心它的具体值。
"""
_ = load_dotenv(find_dotenv())
userModel = os.getenv("MODEL")

clinet = OpenAI(
    api_key = os.getenv("OPENAI_API_KEY"),
    base_url= os.getenv("OPENAI_API_BASE")
)


def get_completion(messages,model = userModel):
   
    response = clinet.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0,
        seed=1024,
        tool_choice="auto",
        tools=[{
            "type":'function',
            "function":{
                "name":'get_location_coordinate',
                "description":"根据 POI 名称，获得 POI 经纬度坐标",
                "parameters":{
                    "type":"object",
                    "properties":{
                        "location":{
                            "type":"string",
                            "description":"POI 名称,必须是中文",
                        },
                        "city":{
                            "type":"string",
                            "description":"POI所在城市名称,必须是中文",
                        }
                        
                    } ,
                    "required":["location","city"]
                }
            },

        },
        {
            "type":'function',
            "function":{
                "name":"search_nearby_pois",
                "description":"根据经纬度坐标，获得附近 POI 列表",
                "parameters":{
                    "type":"object",
                    "properties":{
                        "longitude":{
                            "type":"string",
                            "description":" 中心点精度",
                        },
                        "latitude":{
                            "type":"string",
                            "description":" 中心点纬度",
                        },
                        "keyword":{
                            "type":"string",
                            "description":" 目标 POI关键字",
                        }
                         
                },          
                "required":["longitude","latitude","keyword"],
                }
            }
        }],
    )
   
    return response.choices[0].message



def get_location_coordinate(location,city="天津"):
     url = f"https://restapi.amap.com/v5/place/text?key={amap_key}&keywords={location}&region={city}"
     print(url)
     r = requests.get(url)
     result = r.json()
     if 'pois' in result and result["pois"]:
          return result["pois"][0]
     return None

def search_nearby_pois(longitude,latitude,keyword):
     url =  f"https://restapi.amap.com/v5/place/around?key={amap_key}&keywords={keyword}&location={longitude},{latitude}"
     print(url)
     r = requests.get(url)
     result = r.json()
     ans = ''
    #  result 中是否包含一个名为 "pois" 的键，并且该键的值不为空
     if 'pois' in result and result["pois"]:
          for i in range(min(3,len(result["pois"]))):
               name = result["pois"][i]["name"]
               address = result["pois"][i]["address"]
               distance = result["pois"][i]["distance"]
               ans += f"{name} \n{address} \n{distance}米\n"
     return ans
          
def chat():
    prompt = '天津河东区太阳城附近的咖啡馆有哪些?'
    message = [
        {'role':'system','content':'你是一个地图通，你可以找到任何地址'},
        {'role':'user','content':prompt},
    ]

    response = get_completion(message)
   

    if(response.content  is None):
        response.content = ''
    message.append(response)
    print("---GPT回复---")
    print(response)

    # 如果返回了函数调用的结果，则
    while(response.tool_calls is not None):
        for tool_call in response.tool_calls:
            args = json.loads(tool_call.function.arguments)
            print("输出函数参数值:")
            print(args)
            if(tool_call.function.name == 'get_location_coordinate'):
                print("==函数名==")
                print("Call :get _location_coordinate")
                result = get_location_coordinate(**args)
            elif(tool_call.function.name == 'search_nearby_pois'):
                print("==函数名==")
                print("Call:search_nearby_pois")
                result = search_nearby_pois(**args)
            print("==函数返回==")
            print(result)
            message.append(
                {'role':'tool','content':str(result),"tool_call_id":tool_call.id,"name":tool_call.function.name}
            )
            print("==Message-1==")
            print(message)
            response = get_completion(message)
            if(response.content  is None):
                response.content = ''
            message.append(response)
            print("==Message-2==")
            print(message)
    print("==最终回复==")
    print(response.content)


if __name__ == '__main__':
     chat()